<template>
  <div class="app-container">
    
    <el-row :gutter="20">
      <el-col :span="5">
        <div class="grid-content bg-purple" >
          <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </div>
      </el-col>
      <el-col :span="19">
        <div class="filter-container">
           <el-input  @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入机构名称" v-model="listQuery.organName"></el-input>
           <el-button class="filter-item" type="primary" style="float:right;"  icon="el-icon-edit"  @click="handleCreate">新增</el-button>
           <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;" v-waves icon="el-icon-search" @click="handleFilter">查询</el-button>
        </div>
        <div class="grid-content bg-purple">
          <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
            style="width: 100%">
            <el-table-column align="center" label="行号" width="65">
              <template slot-scope="scope">
                <span>{{scope.$index+1}}</span>
              </template>
            </el-table-column>
            <el-table-column style="width:350px;" v-if="1===2"  align="center" label="主键">
              <template slot-scope="scope">
                <span>{{scope.row.id }}</span>
              </template>
            </el-table-column>
            <el-table-column width="150px" align="center" label="日期">
              <template slot-scope="scope">
                <span>{{scope.row.gmtCreate | formatDatetime}}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="150px" label="机构名称">
              <template slot-scope="scope">
                <span class="link-type" >{{scope.row.organName}}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="150px" label="机构编码">
              <template slot-scope="scope">
                <span class="link-type" >{{scope.row.organCode}}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="150px" label="关联机构">
              <template slot-scope="scope">
                <span class="link-type" >{{scope.row.organLink}}</span>
              </template>
            </el-table-column>
            <el-table-column width="110px" align="center" label="备注">
              <template slot-scope="scope">
                <span>{{scope.row.remark}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
              <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="success" size="mini" @click="handleDetail(scope.row)">详情</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>

          <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
              <el-input type="hidden" v-model="temp.id"></el-input>
              <el-form-item label="机构名称" prop="organName">
                <el-input v-model="temp.organName" placeholder="请输入机构名称" ></el-input>
              </el-form-item>
              <el-form-item label="机构编码" prop="organCode">
                <el-input v-model="temp.organCode" placeholder="请输入机构编码"></el-input>
              </el-form-item>
              <el-form-item label="机构类型" prop="organType">
                <el-input v-model="temp.organType" placeholder="请输入机构类型"></el-input>
              </el-form-item>
              <el-form-item label="机构关联" prop="organLink">
                <el-input v-model="temp.organLink" placeholder="请输入关联机构"></el-input>
              </el-form-item>
              <el-form-item label="remark" prop="remark">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="temp.remark">
                </el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">cancel</el-button>
              <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">confirm</el-button>
              <el-button v-else type="primary" @click="updateData">confirm</el-button>
            </div>
          </el-dialog>

          <el-dialog title="detail" :visible.sync="dialogDetailVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
              <el-input type="hidden" v-model="temp.id"></el-input>
              <el-form-item label="机构名称" prop="organName">
                <el-input v-model="temp.organName" placeholder="请输入机构名称" ></el-input>
              </el-form-item>
              <el-form-item label="机构编码" prop="organCode">
                <el-input v-model="temp.organCode" placeholder="请输入机构编码"></el-input>
              </el-form-item>
              <el-form-item label="机构类型" prop="organType">
                <el-input v-model="temp.organType" placeholder="请输入机构类型"></el-input>
              </el-form-item>
              <el-form-item label="机构关联" prop="organLink">
                <el-input v-model="temp.organLink" placeholder="请输入关联机构"></el-input>
              </el-form-item>
              <el-form-item label="remark" prop="remark">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="temp.remark">
                </el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="dialogDetailVisible = false">CLOSE</el-button>
            </span>
          </el-dialog>
        </div>
      </el-col>
    </el-row>
  </div>
  
</template>

<script>
import { fetchList, fetchUcService, createUcService, updateUcServe } from '@/api/ucService'
import { getTreeOrganList, getPageOrganList, getOrganDetail, addOrgan, delOrgan, updateOrgan } from '@/api/ucorgan'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime, formatDate, formatDatetime  } from '@/utils'
  export default {
    name: 'ucServiceTable',
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: null,
        listLoading: true,
        dialogFormVisible: false,
        dialogDetailVisible:false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        listQuery: {
          organName: '',
          organParentId:"000000",
          page: 1,
          limit: 20,
          serviceName: '',
          sort: '+id'
        },
        temp: {
          id: '',
	        organName: '',
	        organCode: '',
	        organType: '',
	        organLink: '',
	        organParentId: '',
          remark: '',
          isDeleted: 0,
          gmtCreate: null,
          gmtModified: null
        },
        data: [],
        defaultProps: {
          children: 'children',
          label: 'label',
          id: 'id'
        },
        rules: {
          organName: [{ required: true, message: 'organName is required', trigger: 'change' }],
          organCode: [{ required: true, message: 'organCode is required', trigger: 'change' }],
          organLink: [{ required: true, message: 'organLink is required', trigger: 'change' }],
          remark: [{ required: true, message: 'remark is required', trigger: 'change' }],
        }
      };
    },
    filters: {
      formatDate(time) {
        var date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm');
      },
      formatDatetime(time){
        return formatDatetime(time);
      }  
    },
    created() {
      this.getList();
      this.getTreeList();
    },
    methods: {
      getList() {
        this.listLoading = true
        const param = {
          'body': {
            "ucOrganDTO":{
              "organName": this.listQuery.organName,
              "organParentId": this.listQuery.organParentId,
              "isDeleted":"0",
              "remark":"山东高速集团总公司上"
            },
            "pageInfo":{
              "page":this.listQuery.page,
              "pageSize":this.listQuery.limit
            }
          }
        }
        getPageOrganList(param).then(response => {
          this.list = response.body.ucOrganDTOList
          this.total = response.body.pageInfo.rowCount
          this.listLoading = false
        })
      },
      getTreeList() {
        const treeparam = {
          'body': {
            "treeDTO":{
              "id":'',
              "label":''
            }
          }
        }
        getTreeOrganList(treeparam).then(response => {
          this.data = response.body.treeDTOList
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      resetTemp() {
        this.temp = {
          id: '',
	        organName: '',
	        organCode: '',
	        organType: '',
	        organLink: '',
	        organParentId: '',
          remark: '',
          isDeleted: 0,
          gmtCreate: null,
          gmtModified: null
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleNodeClick(data) {
         this.listQuery.organParentId = data.id;
         this.getList();
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const data = {
              'body': {
                "ucOrganDTO":{
                  "organName": this.temp.organName,
                  "organCode": this.temp.organCode,
                  "organType": this.temp.organType,
                  "organLink": this.temp.organLink,
                  "organParentId": this.listQuery.organParentId,
                  "isDeleted":"0",
                  "remark": this.temp.remark
                }
              }
            }
            this.temp.isDeleted = 0
            addOrgan(data).then(response => {
              this.list.unshift(response.body.ucOrganDTO)
              this.getTreeList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.gmtModified = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // const tempData = Object.assign({}, this.temp)
            const data = {
              'body': {
                "ucOrganDTO":{
                  "id": this.temp.id,
                  "organName": this.temp.organName,
                  "organCode": this.temp.organCode,
                  "organType": this.temp.organType,
                  "organLink": this.temp.organLink,
                  "organParentId": this.listQuery.organParentId,
                  "isDeleted":"0",
                  "remark": this.temp.remark
                }
              }
            }
            updateOrgan(data).then(response => {
              const ucOrganDTO = response.body.ucOrganDTO;
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, ucOrganDTO)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row';
        } else if (rowIndex === 3) {
          return 'success-row';
        }
        return '';
      },
      handleDelete(row) {
        const data = {
            'body': {
                "ucOrganDTO":{
                  "id": row.id,
                  "isDeleted": 1
                }
              }
            }
            updateOrgan(data).then(response => {
              const ucOrganDTO = response.body.ucOrganDTO;
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, ucOrganDTO)
                  break
                }
              }
              this.getTreeList()
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      },
      handleDetail(row) {   
          this.temp = Object.assign({}, row) // copy obj
          this.dialogDetailVisible = true
      },
      //下拉框选中事件
      selectGet(vId){//这个vId也就是value值
        let obj = {};
        obj = this.data.find((item)=>{//这里的userList就是上面遍历的数据源
            console.log(item.id+" "+item.label)
            return item.id === vId;//筛选出匹配数据
        });
        this.temp.appId = obj.id;
        this.temp.appName = obj.label;
      }
    }
  };
</script>
<style>
  .el-row {
    margin-bottom: 20px;
    
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    /* background: #d3dce6; */
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>